package com.first.run.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.first.run.constant.SysConstants;
import com.first.run.entity.SysUser;
import com.first.run.service.SysUserService;
import com.first.run.utils.R;
import lombok.AllArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

@RestController
@AllArgsConstructor
@RequestMapping("/unauthorized")
public class SysUserController {


    @GetMapping("/unauthc")
    public Object unauthc() {
        return SysConstants.unauthcMsg;
    }


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public R login(String username, String password) {
        System.out.println("1.用户login接口");

        System.out.println(username+"-----"+password);
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        //用户登录先走login该接口  然后验证是否已经登录 subject.isAuthenticated()
        //如果已经是登录状态  则直接返回token
        //如果没有登录则进行身份验证

        System.out.println("subject.isAuthenticated() = " + subject.isAuthenticated());
        System.out.println("subject = " + subject.getPrincipal());


        String msg = SysConstants.success;
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            msg = SysConstants.unknownAccount;
        } catch (DisabledAccountException e) {
            msg = SysConstants.disabledAccount;
        } catch (IncorrectCredentialsException e) {
            msg = SysConstants.incorrectCredentials;
        } catch (UnauthorizedException e){
            msg = e.getMessage();
        } catch (Throwable e) {
            msg = SysConstants.throwableMsg;
        }

        System.out.println("msg = " + msg);
        System.out.println("token = " + JSON.toJSONString(token));
        return R.ok(token);
    }



}
